// 登录与注册模块
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api';
import { setToken, getToken, removeToken } from '@/utils/token';
const state = {
    code: '',
    // token: localStorage.getItem('TOKEN'),
    token: getToken(),
    userInfo: {}
};
const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        // 获取验证码的接口：直接把验证码返回了，但正常情况是后台把验证码发到用户手机上
        let result = await reqGetCode(phone);
        console.log(result);
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'OK';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 用户注册
    async getRegister({ commit }, data) {
        let result = await reqUserRegister(data);
        // console.log(result);
        if (result.code == 200) {
            // commit('GETREGISTER', result.data);
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 用户登录【token】
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        // 服务器下发token,用户唯一标识符（uuid），将来经常通过带token找服务器要用户信息进行展示
        console.log(result);
        if (result.code == 200) {
            // 用户已经登陆成功而且获取到了token
            commit('USERLOGIN', result.data.token);
            // 持久化存储token
            // localStorage.setItem('TOKEN', result.data.token);
            setToken(result.data.token);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 获取用户信息
    async getUseInfo({ commit }) {
        let result = await reqUserInfo();
        // console.log(result);
        if (result.code == 200) {
            commit('GETUSEINFO', result.data)
            return 'ok'
        }
        else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 退出登录
    async userLogout({ commit }) {
        // 只是向服务器发起一次请求，通知服务器清除token
        let result = await reqLogout();
        // action里面不能操作state，提交mutation修改state
        if (result.code == 200) {
            commit('CLEAR');
            return 'ok';
        } else {
            return Promise(new Error('faile'));
        }
    }

};
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    GETUSEINFO(state, userInfo) {
        state.userInfo = userInfo;
    },
    // 清除自己本地的数据
    CLEAR(state) {
        state.token = '';
        state.userInfo = {};
        // 本地存储数据清空
        removeToken();

    },

};
const getters = {};
export default {
    state,
    actions,
    mutations,
    getters
}
